#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <malloc.h>

#include "armsdkerr.h"
#include "armsdkcmdhist.h"



cmdHistList_t *create_cmdHist_node(CHR *cmd_str)
{
    cmdHistList_t *new_cmdStr = (cmdHistList_t *)malloc(sizeof(cmdHistList_t));
    if (new_cmdStr == NULL)
    {
        MEM_LLOC_ERR(NULL);
    }

    MEMSET(new_cmdStr, 0, sizeof(cmdHistList_t));

    STRCPY(new_cmdStr->au1CmdHistStr, cmd_str);
    new_cmdStr->next = NULL;

    return new_cmdStr;
}

INT4 add_cmdHist(CHR *cmd_str)
{
    cmdHistList_t *new_cmdStr = NULL;
    cmdHistList_t *cur_cmdStr = &gcmdHistHead;

    while (cur_cmdStr->next != NULL)
    {
        cur_cmdStr = cur_cmdStr->next;
    }

    if (MEMCMP(cur_cmdStr->au1CmdHistStr, cmd_str, strlen(cmd_str)) == 0)
    {
        return SUCCESS;
    }
    new_cmdStr = create_cmdHist_node(cmd_str);

    cur_cmdStr->next = new_cmdStr;
    new_cmdStr->prev = cur_cmdStr;
    gcmdHistHead.prev = new_cmdStr;

    return SUCCESS;
}

CHR *last_cmdHist(cmdHistList_t **cmd_node)
{
    if (*cmd_node == NULL)
    {
        *cmd_node = gcmdHistHead.prev;
        return (*cmd_node)->au1CmdHistStr;
    }
    if ((*cmd_node)->prev == &gcmdHistHead)
    {
        return (*cmd_node)->au1CmdHistStr;
    }

    *cmd_node = (*cmd_node)->prev;

    return (*cmd_node)->au1CmdHistStr;
}

CHR *next_cmdHist(cmdHistList_t **cmd_node)
{
    if ((*cmd_node) == NULL)
    {
        return NULL;
    }

    if ((*cmd_node)->next != NULL)
    {
        *cmd_node = (*cmd_node)->next;
        return (*cmd_node)->au1CmdHistStr;
    }
    else
    {
        *cmd_node = NULL;
        return NULL;
    }
}

INT4 update_cmdHist(cmdHistList_t *cmd_node, CHR *cmd_str)
{
    if (MEMCMP(cmd_node->au1CmdHistStr, cmd_str, strlen(cmd_str)) != 0)
    {
        return add_cmdHist(cmd_str);
    }

    if (cmd_node->next == NULL)
    {
        return SUCCESS;
    }

    cmdHistList_t *prev_node = cmd_node->prev;
    cmdHistList_t *next_node = cmd_node->next;
    prev_node->next = next_node;
    next_node->prev = prev_node;

    while (next_node->next != NULL)
    {
        next_node = next_node->next;
    }
    next_node->next = cmd_node;
    cmd_node->prev = next_node;
    cmd_node->next = NULL;
    gcmdHistHead.prev = cmd_node;

    return SUCCESS;
}

INT4 destroy_cmdHist()
{
    if (gcmdHistHead.next == NULL)
    {
        return SUCCESS;
    }

    cmdHistList_t *cur_cmdStr = gcmdHistHead.next;
    cmdHistList_t *next_cmdStr = NULL;

    while (cur_cmdStr->next != NULL)
    {
        next_cmdStr = cur_cmdStr->next;
        free(cur_cmdStr);
        cur_cmdStr = next_cmdStr;
    }

    /* 释放最后一个节点 */
    free(cur_cmdStr);
    gcmdHistHead.prev = NULL;
    gcmdHistHead.next = NULL;

    return SUCCESS;
}

